<template>
  <div class="page-content-root" v-loading="loading">

    <el-collapse-transition>
      <div class="query-container" v-show="!currentUserId || currentUserId === ''">
        <query-select class="map-q-item" @submit="attQuery"></query-select>
        <area-select class="map-q-item" v-model="area"></area-select>
      </div>
    </el-collapse-transition>

<!--    <el-button v-if="bufferUserId !== ''" roun @click="startPlayer" size="mini" style="position: absolute;top: 10px;left: 50%;z-index: 99">轨迹播放</el-button>-->



    <lark-map @loaded="load" ref="mmap" :map-config="bufferMapConfig" :query-back-fun="queryBackFun"
              :before-query="beforeQuery"
              :after-query="afterQuery"></lark-map>


    <div style="display: none">
      <el-tabs v-model="activeName" ref="tabs">
        <el-tab-pane v-for="(item, index) in tabsData" :key="`${item.layerId}_${index}`" :label="item.layerName"
                     :name="item.layerId.toString()">
          <div class="table-container">
            <el-button roun @click="startPlayer" v-if="item.layerName === '采集人'" size="mini">轨迹播放</el-button>
            <lark-value-table :data="item.tableData" width="100%"
                              :height="item.layerName === '采集人'?'90%':'100%'" :column-number="2"></lark-value-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-collapse-transition>
      <div class="player-container" :style="playerContainerStyle"
           v-if="view != null && currentUserId && currentUserId !== ''">
        <tack-play-back :view="view" :user-id="currentUserId"
                        :init-show="true" @load="setFinish" @exit="exitPlayer"></tack-play-back>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, computed, nextTick, watch } from '@vue/composition-api'
  import mapConfig from '../../../../datas/mapConfig'
  import { Message, MessageBox } from 'element-ui'
  import store from '@/store'
  import router from '@/router'
  import { draw } from 'lark-map'
  import areaSelect from '@/components/ServiceComponents/areaSelect'
  import querySelect from '@/components/ServiceComponents/querySelect'
  import {
    queryResultsByUrls,
    highlightByGeometryList,
    getGeometryListByQueryResult,
    getTabsDataByQueryResult,
    getOnlyResByQueryResult,
    removeHighlight,
    queryGraphicByAttribute,
    getGraphicList,
    getGraphicByGeometry,
    addGraphicLayer
  } from 'lark-map'
  import { MathUtil } from 'lark-utils'
  import { onlineUser } from '@/api/industry/ctl'
  import tackPlayBack from '@/components/ServiceComponents/tackPlayBack'

  export default {
    name: 'pageContent',
    props: {},
    components: {
      areaSelect,
      querySelect,
      tackPlayBack
    },
    setup(props, content) {

      let {} = props


      const playerContainerStyle = computed(() => {
        return { left: `${(window.innerWidth - 575) / window.innerWidth * 100 / 2}%` }
      })

      const data = reactive({
        view: null,
        bufferMapConfig: mapConfig,
        loading: true,
        area: [],
        playerContainerStyle,
        activeName: '',
        tabsData: [],
        onlineUserGraphicLayer: null,
        onlineUserNameGraphicLayer: null,
        currentUserId: '',
        finish: null,
        bufferUserId: ''
      })

      const load = view => {
        if (view?.mapView) {
          data.view = view.mapView
          data.loading = false
          loadOnlineUser()
          setInterval(() => {
            loadOnlineUser()
          }, 60000)
        }
      }

      const finishPlayer = () => {
        if (data.finish && typeof data.finish === 'function' && data.currentUserId && data.currentUserId !== '') {
          data.finish()
        }
        data.currentUserId = ''
        data.bufferUserId = ''
        content.emit('endPalyer')
      }

      const startPlayer = () => {
        let { view } = data
        view.popup.close()
        content.emit('startPalyer')
        setTimeout(() => {
          data.currentUserId = data.bufferUserId
        }, 5)
      }

      const exitPlayer = () => {
        data.currentUserId = ''
        finishPlayer()
      }

      const queryBackFun = (res, mapPoint) => {
        let { view, onlineUserGraphicLayer: graphicLayer } = data

        let currentUser = getGraphicByGeometry({ graphicLayer, geometry: mapPoint })

        if (currentUser?.length) {
          data.bufferUserId = currentUser[0].attributes.userId
        } else {
          finishPlayer()
        }

        let onlyRes = getOnlyResByQueryResult({ res, mapPoint })

        !onlyRes?.length && removeHighlight(view)

        if (!onlyRes?.length && !currentUser?.length) {
          return
        }

        let attList = onlyRes?.length ? getTabsDataByQueryResult(onlyRes) : []

        if (currentUser?.length) {
          attList.push({
            layerId: 0,
            layerName: '采集人',
            tableData: currentUser.map(item => {
              let { attributes: { nickName } } = item
              return { nickName }
            })
          })
        }

        data.tabsData = attList.map(item => {

          let { tableData, layerId, layerName } = item

          let [currentTableData] = tableData

          let itemRes = {
            layerId: `${layerId}_${MathUtil.guid()}`,
            layerName
          }

          itemRes.tableData = Object.keys(currentTableData).filter(key => {
            let bufferKey = key.toUpperCase()
            return bufferKey !== 'OBJECTID' && bufferKey !== 'SHAPE' && bufferKey !== 'SHAPE.AREA' && bufferKey !== 'SHAPE.LEN' && bufferKey !== 'X' && bufferKey !== 'Y'
          }).map(key => {
            return { label: key === 'nickName' ? '采集人' : key, value: currentTableData[key] }
          })

          return itemRes
        })

        data.activeName = data.tabsData[0].layerId.toString()

        let geometryList = getGeometryListByQueryResult({ res: onlyRes, merge: true })
        highlightByGeometryList({ view, geometryList, zoom: false })

        return content.refs.tabs.$el
      }

      const beforeQuery = () => {
        data.loading = true
      }

      const afterQuery = () => {
        data.loading = false
      }

      const aDraw = async type => {
        let { view } = data
        if (!view) return
        let graphic = await draw({ type, view })
      }

      const getQueryConfig = ({ queryType, where, subLayerIds, inputValue }) => {

        let { view } = data

        let result = {
          view,
          idList: [],
          outFields: [],
          where: [],
          returnGeometry: [],
          subLayerIds: []
        }

        switch (queryType) {
          case 'ChinaAdminService' :
            result.idList.push('ChinaAdminService')
            result.outFields.push({ parentId: 'ChinaAdminService', value: ['*'] })
            result.where.push({ parentId: 'ChinaAdminService', value: where })
            result.returnGeometry.push({ parentId: 'ChinaAdminService', value: true })
            result.subLayerIds.push({ parentId: 'ChinaAdminService', value: subLayerIds })
            break

          case 'zzzy' :
            let whereValue = `FAMILY LIKE '%${inputValue}%' or GENUS LIKE '%${inputValue}%' or NAME LIKE '%${inputValue}%' or IDENTIFY_USER_ID LIKE '%${inputValue}%' or LOCATION LIKE '%${inputValue}%' or CLT_USER_ID LIKE '%${inputValue}%' or GENUS LIKE '%${inputValue}%'`
            result.idList.push('GermplasmResourceService')
            result.outFields.push({ parentId: 'GermplasmResourceService', value: ['*'] })
            result.where.push({ parentId: 'GermplasmResourceService', value: whereValue })
            result.returnGeometry.push({ parentId: 'GermplasmResourceService', value: true })
            result.subLayerIds.push({ parentId: 'GermplasmResourceService', value: [0] })
            break

          case 'zzzyk' :
            result.idList.push('GpmBlankService')
            result.outFields.push({ parentId: 'GpmBlankService', value: ['*'] })
            result.where.push({ parentId: 'GpmBlankService', value: `NAME like '%${inputValue}%'` })
            result.returnGeometry.push({ parentId: 'GpmBlankService', value: true })
            result.subLayerIds.push({ parentId: 'GpmBlankService', value: [0] })
            break

          case 'bbk' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'trk' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'ywcj' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'jgzx' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'czt' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'zyp' :
            result.idList.push('NmgCityService')
            result.outFields.push({ parentId: 'NmgCityService', value: ['*'] })
            result.where.push({ parentId: 'NmgCityService', value: `CODE = '${inputValue}'` })
            result.returnGeometry.push({ parentId: 'NmgCityService', value: true })
            result.subLayerIds.push({ parentId: 'NmgCityService', value: [2] })
            break

          case 'sys' :
            result.idList.push('LaboratoryService')
            result.outFields.push({ parentId: 'LaboratoryService', value: ['*'] })
            result.where.push({ parentId: 'LaboratoryService', value: `NAME like '%${inputValue}%'` })
            result.returnGeometry.push({ parentId: 'LaboratoryService', value: true })
            result.subLayerIds.push({ parentId: 'LaboratoryService', value: [0] })
            break

          default:
            break
        }

        return result

      }

      const attQuery = async(config) => {
        let { view } = data
        if (!view) return
        data.loading = true
        let res = await queryResultsByUrls(getQueryConfig(config))

        let geometryList = getGeometryListByQueryResult({ res, merge: true })

        if (!geometryList?.length) {
          data.loading = false
          Message.warning('没有查询结果')
          removeHighlight(view)
          return
        }

        highlightByGeometryList({ view, geometryList: getGeometryListByQueryResult({ res, merge: true }), zoom: true })
        data.loading = false
      }

      const addGraphicPoints = (points, symbol, graphicLayer) => {
        if (!points?.length) {
          return
        }
        let pointList = []
        for (let i = 0; i < points.length; i++) {
          let { x, y, attributes = {}, symbol: selfSymbol = null } = points[i]
          if (!x || !y) {
            continue
          }
          pointList.push({
            attributes: { ...attributes }, symbol: selfSymbol, geometryType: 'point', point: [x, y]
          })
        }

        let par = {
          config: pointList, spatialReference: {
            'wkid': 4490
          }
        }
        if (symbol) par.symbol = symbol

        let graphicList = getGraphicList(par)
        if (!graphicList) {
          return
        }
        if (graphicLayer) {
          graphicLayer.addMany(graphicList)
        } else {
          graphicLayer = addGraphicLayer({ view: data.view, graphicList: graphicList })
        }
        return graphicLayer
      }

      const loadOnlineUser = async() => {

        let response = await onlineUser()
        let redata = response.data
        // let redata = [{
        //   longitude: 111.3509783068922,
        //   latitude: 40.89799873115123,
        //   id: 137,
        //   userId: 'MC005299',
        //   nickName: '乔冬'
        // }]

        if (data.onlineUserGraphicLayer != null && data.onlineUserNameGraphicLayer != null) {
          redata = redata.filter(({ longitude, latitude, id, userId, nickName }) => {
            let graphic = queryGraphicByAttribute({ conditions: { id }, graphicLayer: data.onlineUserGraphicLayer })
            let textGraphic = queryGraphicByAttribute({
              conditions: { id },
              graphicLayer: data.onlineUserNameGraphicLayer
            })
            if (graphic != null && graphic.length > 0) {
              let { x, y } = graphic[0].geometry
              if (x != longitude || y != latitude) {
                //移除graphic,后面新增
                data.onlineUserGraphicLayer.remove(graphic[0])
                data.onlineUserNameGraphicLayer.remove(textGraphic[0])
                return true
              }
            }
            return false
          })
          data.onlineUserGraphicLayer.load()
        }

        if (redata.length == 0) return
        let points = redata.map(({ longitude: x, latitude: y, id, userId, nickName }) => {
          return { x, y, attributes: { id, userId, nickName } }
        })
        let symbol = {
          type: 'picture-marker',
          url: '',
          width: 28 / 1.5,
          height: 41 / 1.5,
          outline: true
        }
        //图像
        let gl = addGraphicPoints(points, symbol, data.onlineUserGraphicLayer)
        if (data.onlineUserGraphicLayer == null) {
          data.onlineUserGraphicLayer = gl
        }

        //文字
        let textPoints = JSON.parse(JSON.stringify(points)).map(t => {
          t.symbol = {
            type: 'text',  // autocasts as new TextSymbol()
            color: '#9065fa',
            haloColor: 'white',//给字体加框
            haloSize: '1px',
            text: t.attributes.nickName,
            xoffset: -1,
            yoffset: -20,
            font: {
              size: 12,
              family: 'microsoft-yahei',
              weight: 'bold'
            }
          }
          return t
        })
        let textgl = addGraphicPoints(textPoints, null, data.onlineUserNameGraphicLayer)
        if (data.onlineUserNameGraphicLayer == null) {
          data.onlineUserNameGraphicLayer = textgl
        }
      }

      const setFinish = ({ finish }) => {
        data.finish = finish
      }

      watch(() => data.area, val => {
        let { view } = data

        if (!val?.length) {
          removeHighlight(view)
          return
        }

        let [province, city, county] = val
        let subLayerIds = []
        let where = ''
        let queryType = 'ChinaAdminService'

        if (county && county !== '') {
          subLayerIds.push(2)
          where = `CODE = '${county}'`
          attQuery({ subLayerIds, queryType, where })
          return
        }

        if (city && city !== '') {
          subLayerIds.push(3)
          where = `CODE = '${city}'`
          attQuery({ subLayerIds, queryType, where })
          return
        }

        if (province && province !== '') {
          subLayerIds.push(4)
          where = `CODE = '${province}'`
          attQuery({ subLayerIds, queryType, where })
        }
      })

      return {
        ...toRefs(data),
        load,
        queryBackFun,
        beforeQuery,
        afterQuery,
        aDraw,
        attQuery,
        setFinish,
        startPlayer,
        exitPlayer
      }
    }
  }
</script>

<style scoped lang="scss">
  $full: 100%;
  .page-content-root {
    width: 100%;
    height: 100%;
    position: relative;

    .query-container {
      position: absolute;
      top: 4vh;
      z-index: 20;
      display: flex;
      flex-direction: row;
      width: 30vw;
      height: 4vh;
      left: 35vw;

      .map-q-item {
        flex: 1;
        margin-right: 30px;

        &.query-select-root {
          flex-basis: 80px;
        }
      }
    }

    .player-container {
      position: absolute;
      bottom: 20px;
      z-index: 20;
      display: flex;
      flex-direction: row;
    }
  }
</style>
<style lang="scss">
</style>
